package com.deer.wms.base.system.web.bill;

import com.deer.wms.base.system.model.bill.*;
import com.deer.wms.base.system.model.box.BoxItem;
import com.deer.wms.base.system.model.box.BoxItemCriteria;
import com.deer.wms.base.system.model.box.BoxItemDto;
import com.deer.wms.base.system.model.item.ItemInfo;
import com.deer.wms.base.system.model.item.ItemInfoDto;
import com.deer.wms.base.system.model.item.ItemInfoParam;
import com.deer.wms.base.system.model.item.ItemSpecification;
import com.deer.wms.base.system.model.task.PickTask;
import com.deer.wms.base.system.model.task.PickTaskDto;
import com.deer.wms.base.system.service.bill.BillOutSapService;
import com.deer.wms.base.system.service.bill.IBillOutDetailService;
import com.deer.wms.base.system.service.bill.IBillOutMasterService;
import com.deer.wms.base.system.service.box.IBoxItemService;
import com.deer.wms.base.system.service.item.IItemInfoService;
import com.deer.wms.base.system.service.item.ItemSpecificationService;
import com.deer.wms.base.system.service.task.PickTaskService;
import com.deer.wms.base.system.service.zh.WorkTasksService;
import com.deer.wms.common.annotation.Log;
import com.deer.wms.common.core.controller.BaseController;
import com.deer.wms.common.core.domain.AjaxResult;
import com.deer.wms.common.core.page.TableDataInfo;
import com.deer.wms.common.core.result.Code;
import com.deer.wms.common.core.result.Result;
import com.deer.wms.common.core.result.ResultGenerator;
import com.deer.wms.common.core.text.Convert;
import com.deer.wms.common.enums.BusinessType;
import com.deer.wms.common.utils.poi.ExcelUtil;
import com.deer.wms.framework.util.ShiroUtils;
import com.deer.wms.system.domain.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


/**出库单*/
@Controller
@RequestMapping("/out/billOutMaster")
public class BillOutMasterController extends BaseController {

    private String prefix = "out/billOutMaster";

    @Autowired
    private IBillOutMasterService billOutMasterService;
    @Autowired
    private IBillOutDetailService billOutDetailService;
    @Autowired //物料
    private IItemInfoService itemInfoService;
    @Autowired //库存
    private IBoxItemService iBoxItemService;
    @Autowired //工作任务
    private WorkTasksService workTasksService;
    @Autowired
    private BillOutSapService billOutSapService;

    @PostMapping("/findBillOutMasterDtoByBillNo")
    @ResponseBody
    public BillOutMasterDto findBillOutMasterDtoByBillNo(String billNo){
       return billOutMasterService.findBillOutMasterDtoByBillNo(billNo);
    }

    @GetMapping("/billOutPlan")
    public String billOutPlan() { return prefix + "/billOutPlan"; }
    @GetMapping("/billOutPlanMSG")
    public String billOutPlanMSG() { return prefix + "/billOutPlanMSG"; }

    @GetMapping("/billOutPlanAdd")
    public String billOutPlanAdd() { return prefix + "/billOutPlanAdd"; }

    @GetMapping("/billOutPlanDetail")
    public String billOutPlanDetail() { return prefix + "/billOutPlanDetail"; }

    /*查询出库单列表*/
    @RequiresPermissions("out:billOutMaster:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BillOutMasterDto billOutMasterDto) {
        startPage();
        List<BillOutMasterDto> list = billOutMasterService.selectBillOutMasterList(billOutMasterDto);
        return getDataTable(list);
    }

    /*出库流水查询*/
    @PostMapping("/selectDetailStreamList")
    @ResponseBody
    public TableDataInfo selectDetailStreamList(BillOutDetailDeviceDto detailDevice) {
        startPage();
        List<BillOutDetailDeviceDto> list = billOutMasterService.selectDetailStreamList(detailDevice);
        BillOutDetailDeviceDto detailAll = new BillOutDetailDeviceDto();
        detailAll.setBatch(detailDevice.getBatch())
                .setItemCode(detailDevice.getItemCode())
                .setStartTime(detailDevice.getStartTime())
                .setEndTime(detailDevice.getEndTime())
                .setDeviceName(detailDevice.getDeviceName());
        BillOutDetailDeviceDto detailSum = billOutMasterService.getDetailSum(detailAll);
        for (BillOutDetailDeviceDto detail : list) {
            detail.setWeightSum(detailSum.getWeightSum());
            detail.setBoxSum(detailSum.getBoxSum());
        }

        return getDataTable(list);
    }
    /*出库计划查询*/
    @PostMapping("/selectBillOutPlan")
    @ResponseBody
    public TableDataInfo selectBillOutPlanList(BillOutPlanDto billOutPlanDto) {
        startPage();
        List<BillOutPlanDto> list = billOutMasterService.selectBillOutPlanList(billOutPlanDto);
        return getDataTable(list);
    }
    /*根据planId查询出库计划*/
    @RequiresPermissions("out:billOutMaster:findBillOutMasterDtoByBillId")
    @PostMapping("/findBillOutPlanByPlanId")
    @ResponseBody
    public BillOutPlanDto findBillOutPlanByPlanId(Integer planId){
        return billOutMasterService.findBillOutPlanByPlanId(planId);
    }

    /*根据出库计划id查询出库明细*/
    @PostMapping("/findBillOutDetailByPlanId")
    @ResponseBody
    public List<BillOutDetailDto> findBillOutDetailByPlanId(Integer billOutPlanId){
        //List<BillOutDetailDto> list = billOutMasterService.findBillOutDetailByPlanId(billOutPlanId);
        //return getDataTable(list);
        return  billOutMasterService.findBillOutDetailByPlanId(billOutPlanId);
    }
    /*根据出库计划id查询未出库明细*/
    @PostMapping("/getBillOutDetailByPlanId")
    @ResponseBody
    public List<BillOutDetailDto> getBillOutDetailByPlanId(Integer billOutPlanId){
        //List<BillOutDetailDto> list = billOutMasterService.findBillOutDetailByPlanId(billOutPlanId);
        //return getDataTable(list);
        return  billOutMasterService.getBillOutDetailByPlanId(billOutPlanId);
    }

    /*查询物料的商家构成*/
    @PostMapping("/findBoxItemByItemId")
    @ResponseBody
    public TableDataInfo findBoxItemByItemId(Integer itemId){
        List<BoxItemDto> list = iBoxItemService.findBoxItemByItemId(itemId);
        return getDataTable(list);
    }
    /*查询物料的批次构成*/
    @PostMapping("/findBoxBatchByItemId")
    @ResponseBody
    public TableDataInfo findBoxBatchByItemId(Integer itemId){
        List<BoxItemDto> list = iBoxItemService.findBoxBatchByItemId(itemId);
        return getDataTable(list);
    }

    /*根据出库明细id查询机台列表明细*/
    @PostMapping("/findDeviceListByDetailId")
    @ResponseBody
    public TableDataInfo findDeviceListByDetailId(BillOutDetail billOutDetail){
        List<BillOutDetailDto> list = billOutMasterService.findDeviceListByDetailId(billOutDetail);
        return getDataTable(list);
    }
    /*根据billId查询出库计划*/
    @PostMapping("/findBillOutPlanByBillId")
    @ResponseBody
    public List<BillOutPlanDto> findBillOutPlanByBillId(Integer billId){
        //List<BillOutPlanDto> list = billOutMasterService.findBillOutPlanByBillId(billId);
        //return getDataTable(list);
        return billOutMasterService.findBillOutPlanByBillId(billId);
    }
    /*根据billId查询出库单信息*/
    @RequiresPermissions("out:billOutMaster:findBillOutMasterDtoByBillId")
    @PostMapping("/findBillOutMasterDtoByBillId")
    @ResponseBody
    public BillOutMasterDto findBillOutMasterDtoByBillId(Integer billId){
        return billOutMasterService.findBillOutMasterDtoByBillId(billId);
    }

    /*未完成的出库单列表*/
    @PostMapping("/waitList")
    @ResponseBody
    public TableDataInfo waitList(BillOutMasterDto billOutMasterDto) {
        startPage();
        List<BillOutMasterDto> list = billOutMasterService.selectWaitBillOutMasterList(billOutMasterDto);
        return getDataTable(list);
    }
    /*机台列表*/
    @PostMapping("/deviceList")
    @ResponseBody
    public TableDataInfo deviceList(DeviceManager deviceManager) {
        startPage();
        List<DeviceManager> list = billOutMasterService.findDeviceList(deviceManager);
        return getDataTable(list);
    }
    /*sap明细物料列表*/
    @PostMapping("/findMATNRByBillId")
    @ResponseBody
    public List<MATNRvo> findMATNRByBillId(Integer billId){

        return billOutMasterService.findMATNRByBillId(billId);
    }
    /*添加与SAP出库单对应的出库计划*/
    @PostMapping("/insertPlan")
    @ResponseBody
    @Transactional
    public Result insertPlan(@RequestBody InserData inserData){
        String userName = ShiroUtils.getLoginName();
        Integer userId = ShiroUtils.getUserId();
        BillOutMaster billOutMaster = inserData.getBillOutMaster();
        List<BillOutDetailDto> billOutDetailList = inserData.getBillOutDetailList();

        /*1.创建对应的SAP*/
        BillOutSapDto billOutSapDto = new BillOutSapDto();
        billOutSapDto.setType(billOutMaster.getType()) //出库类型
                .setCreateName(userName) //创建人
                .setCreateId(userId)
                .setBillState(1).setState(1);
        billOutSapService.insertBillOutSap(billOutSapDto);
        /*2.创建对应的SAP明细*/
        billOutDetailList.forEach(billOutDetail->{
            billOutSapDto.setItemId(billOutDetail.getItemId())
                    .setERFMG(billOutDetail.getWeight())
                    .setMATNR(billOutDetail.getItemCode())
                    .setERFME(billOutDetail.getUnit())
                    .setState(1);
            billOutSapService.insertBillOutSapDetail(billOutSapDto);
        });

        /*3.创建入库计划单*/
        Long outNumber = workTasksService.getBillOutNumber();
        String billNo = "JH" + outNumber;
        billOutMaster.setBillNo(billNo)
                .setOutNumber(outNumber)
                .setSapNo(billOutSapDto.getSapNo())//计划单号
                .setSapId(billOutSapDto.getBillOutSapId())
                .setCreateUserName(userName) //创建人
                .setCreateUserId(userId)
                .setState(1)//1待出库
                .setSapState(1); //过账
        billOutSapService.insertBillOutMaster(billOutMaster);
        return ResultGenerator.genSuccessResult();
    }

    /*添加出库计划下的出库单据*/
    @RequiresPermissions("out:billOutMaster:add")
    @Log(title = "出库单", businessType = BusinessType.INSERT)
    @PostMapping("/insert")
    @ResponseBody
    @Transactional
    public Result insert(@RequestBody InserData inserData){
        /*判断数据合法性*/
        List<BillOutDetailDto> billOutDetailList = inserData.getBillOutDetailList();
        float weight = 0F;
        float erfmg = 0f;
        int itemId = 0;
        for (BillOutDetailDto billOutDetail : billOutDetailList) {
            erfmg = billOutDetail.getErfmg();//总重量
            weight = billOutDetail.getWeight();
            itemId = billOutDetail.getItemId();//物料id
            for (BillOutDetailDto el : billOutDetailList) {
                if(el.getItemId() == itemId && !el.getDeviceName().equals(billOutDetail.getDeviceName())){
                    weight = weight+el.getWeight();
                }
                if(erfmg < weight){
                    return ResultGenerator.genWeightError();//大于计划重量
                }
            }
        }

        String createUserName = ShiroUtils.getLoginName();
        Long planNumber = workTasksService.getPlanNumber();
        String plamNo = "CK" + planNumber;
        /*新建出库单*/
        BillOutPlan billOutPlan = new BillOutPlan();
        billOutPlan.setCreateName(createUserName)
                .setPlanNo(plamNo) //出库单号
                .setPlanNumber(planNumber)//流水号
                .setSapNo(inserData.getBillOutMaster().getSapNo()) //出库工单号
                .setBillId(inserData.getBillOutMaster().getBillId()); //出库单id
        if(inserData.getBillOutMaster().getType() != 3){
            billOutPlan.setState(1);
        }else {
            billOutPlan.setState(3);
        }
        billOutMasterService.insertBillOutPlan(billOutPlan);

        /*创建出库单明细*/
        billOutDetailList.forEach(billOutDetail->{
            billOutDetail.setPlanId(billOutPlan.getBillOutPlanId());//计划id
            if(inserData.getBillOutMaster().getType() != 3){
                billOutDetail.setState(1);
            }else {
                billOutDetail.setState(2);
            }

            billOutMasterService.insertBillOutDetail(billOutDetail);
        });

        return ResultGenerator.genSuccessResult();
    }
    /*出库单据强制完成*/
    @PostMapping("/planOver")
    @ResponseBody
    @Transactional
    public Result planOver(Integer billOutPlanId){
        billOutMasterService.planOver(billOutPlanId);
        billOutMasterService.planDetailOver(billOutPlanId);

        return  ResultGenerator.genSuccessResult();
    }




//    /**
//     * 删除出库单
//     */
//    @RequiresPermissions("out:billOutMaster:remove")
//    @Log(title = "出库单", businessType = BusinessType.DELETE)
//    @PostMapping( "/remove")
//    @ResponseBody
//    @Transactional(rollbackFor = Exception.class)
//    public AjaxResult remove(String ids){
//        String[] Id = Convert.toStrArray(ids);
//        for (String id : Id) {
//            billOutDetailService.deleteBillOutDetailByBillId(Integer.parseInt(id));
//        }
//        return toAjax(billOutMasterService.deleteBillOutMasterByIds(ids));
//    }

    /**
     * 修改保存出库单
     */
    @RequiresPermissions("out:billOutMaster:edit")
    @Log(title = "出库单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result editSave(@RequestBody InserData inserData){
        BillOutMaster billOutMaster = inserData.getBillOutMaster();
        billOutMasterService.updateBillOutMaster(billOutMaster);
        List<BillOutDetailDto> billOutDetails = inserData.getBillOutDetailList();
        billOutDetailService.deleteBillOutDetailByBillId(billOutMaster.getBillId());
        for (BillOutDetail billOutDetail: billOutDetails){
            //billOutDetail.setBillId(billOutMaster.getBillId());
//            if(billOutMaster.getAreaId()==248){
//                billOutDetail.setBatch("");
//            }
            //ItemInfo itemInfo = itemInfoService.findByItemCode(billOutDetail.getItemCode());
            billOutDetailService.saveBillOutDetail(billOutDetail);
        }
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 修改出库单
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer billId, ModelMap mmap)
    {
        BillOutMaster billOutMaster = billOutMasterService.selectBillOutMasterById(billId);
        mmap.put("billOutMaster", billOutMaster);
        List<BillOutDetailDto> billOutDetailDtos = billOutDetailService.findListByBillId(billId);
        mmap.put("billOutDetails",billOutDetailDtos);
        mmap.put("audit",false);
        return prefix + "/edit";
    }

    /**
     * 审核出库单
     */
    @RequiresPermissions("out:billOutMaster:audit")
    @GetMapping("/audit/{id}")
    public String audit(@PathVariable("id") Integer billId, ModelMap mmap) {
        BillOutMaster billOutMaster = billOutMasterService.selectBillOutMasterById(billId);
        mmap.put("billOutMaster", billOutMaster);
        List<BillOutDetailDto> billOutDetailDtos = billOutDetailService.findListByBillId(billId);
        mmap.put("billOutDetails",billOutDetailDtos);
        mmap.put("audit",true);
        return prefix + "/edit";
    }

    /**
     * 出库单通过审核,状态变为1(审核通过)
     * @param billId
     * @return
     */
    @RequiresPermissions("out:billOutMaster:audit")
    @ResponseBody
    @PostMapping("/auditFinish")
    public Result auditFinish(Integer billId){
        billOutMasterService.auditFinish(billId);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 查看详情
     */
    @GetMapping("/detail")
    public String detail()
    {
        return prefix + "/detail";
    }

    /**
     * 新增出库单
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    @RequiresPermissions("out:billOutMaster:view")
    @GetMapping("/page")
    public String billInMaster()
    {
        return prefix + "/billOutMaster";
    }



    /**
     * 查询出库单物料详情
     * @param criteria
     * @return
     */
    @RequiresPermissions("out:billOutMaster:list")
    @PostMapping("/findBoxItemDetails")
    @ResponseBody
    public TableDataInfo findItemDetail(BillOutDetailCriteria criteria){
        startPage();
        List<BillOutDetailDto> list = billOutDetailService.findItemDetails(criteria);
        return getDataTable(list);
    }

    @PostMapping("/findItemInfoCount")
    @ResponseBody
    public AjaxResult findItemInfoCount(BoxItem boxItem){
        Integer count= billOutDetailService.findItemCount(boxItem);
        if(count==null)
        {
            count=0;
        }
        return AjaxResult.success("获取物料库存成功",count);
    }




    /*出库单*/
//    @RequiresPermissions("in:billInMaster:findList")
    @PostMapping("/findList")
    @ResponseBody
    @Transactional
    public TableDataInfo findList(BillOutMasterCriteria billOutMasterCriteria) {
        startPage();
        List<BillOutMasterDto> list = billOutMasterService.findList(billOutMasterCriteria);
        return getDataTable(list);
    }



    /**
     * 导出出库单列表
     */
    @RequiresPermissions("out:billOutMaster:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BillOutMasterDto criteria) {
        List<BillOutMasterDto> list = billOutMasterService.selectBillOutMasterList(criteria);
        ExcelUtil<BillOutMasterDto> util = new ExcelUtil<BillOutMasterDto>(BillOutMasterDto.class);
        return util.exportExcel(list, "出库单列表");
    }
    /**
     * 导出列表
     */
    @RequiresPermissions("out:billOutMaster:partExcel")
    @PostMapping("/partExcel")
    @ResponseBody
    public AjaxResult partExcel(@RequestParam  String ids) {
        List<BillOutMasterDto> byIds=new ArrayList();
        String[] split = ids.split(",");
        for (String s:split
        ) {
            BillOutMasterDto b=new BillOutMasterDto();
            b.setBillId(Integer.parseInt(s));
            List<BillOutMasterDto> list = billOutMasterService.selectBillOutMasterList(b);
            for (BillOutMasterDto bs:list
            ) {
                byIds.add(bs);
            }




        }
        // List<BillInSapDto> billInSapList = billInSapService.findBillInSapDtoList(billInSapCriteria);
        ExcelUtil<BillOutMasterDto> util = new ExcelUtil<BillOutMasterDto>(BillOutMasterDto.class);
        return util.exportExcel(byIds, "出库单");
    }


    @GetMapping("/toNonWorkOrderOut")
    public String toNonWorkOrderOut()
    {
        return prefix + "/nonWorkOrderOut";
    }
}











